<template>
  <el-date-picker
    v-model="value"
    :picker-options="pickerOptions"
    style="vertical-align: middle; margin: 0 10px 10px 0"
    type="daterange"
    range-separator="至"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    value-format="yyyy-MM-dd"
    @change="handelChange"
  />
</template>

<script>
export default {
  name: 'TimeRange',
  data() {
    return {
      value: '',
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '当月',
            onClick(picker) {
              const end = new Date()
              const now = new Date()
              const start = new Date(now.getFullYear(), now.getMonth(), 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '今年',
            onClick(picker) {
              const end = new Date()
              const now = new Date()
              const start = new Date(now.getFullYear(), 0, 1)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  methods: {
    handelChange(val) {
      this.$emit('input', (val && val.join()) || '')
    }
  }
}
</script>
